package com.xydtech.web.controller.common;

import com.xydtech.common.annotation.Log;
import com.xydtech.common.config.ServerConfig;
import com.xydtech.common.config.XydtechBusiPlatConfig;
import com.xydtech.common.constant.Constants;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.file.FileUploadUtils;
import com.xydtech.common.utils.file.FileUtils;
import com.xydtech.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author xydtech
 */
@Controller
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    //文件分布式存储开关
    @Value("${busiplat.minioUpload}")
    private boolean minioUpload;

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysDeptService sysDeptService;
    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            //String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = XydtechBusiPlatConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {

            // 上传文件路径
            String filePath = XydtechBusiPlatConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file, minioUpload);
            String url = serverConfig.getUrl().replaceAll(":443", "") + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", fileName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/common/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = XydtechBusiPlatConfig.getUploadPath();
            List<String> fileNames = new ArrayList<String>();
            List<String> urls = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file, minioUpload);
                //String url = serverConfig.getUrl() + fileName;
                fileNames.add(fileName);
                urls.add(fileName);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = XydtechBusiPlatConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     *指定子目录通用上传请求
     * @Title: uploadFile
     * @param subFilePath 上传子目录（根据业务功能自定义）
     * @param file 文件
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author JHON
     * @Date 2021/10/20 17:06
     **/
    @PostMapping("/common/upload/{subFilePath}")
    @ResponseBody
    public AjaxResult uploadFile(@PathVariable("subFilePath") String subFilePath, MultipartFile file) throws Exception {
        try {
            //当前机构号
            Long deptId = ShiroUtils.getSysUser().getDeptId();
            //根据当前机构查询法人机构
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
            if (dept != null) {
                deptId = dept.getDeptId();
            }
            // 上传文件路径拼接机构号
            String filePath = XydtechBusiPlatConfig.getUploadPath(deptId + "/" + subFilePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file, minioUpload);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            /**路径不带项目名称*/
            ajax.put("url", fileName);
            //文件保存路径
            ajax.put("path", fileName.replaceAll("/profile", XydtechBusiPlatConfig.getProfile()));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     *上传Cropper截图文件,返回图片路径
     * @Title: uploadCropperImage
     * @param file 文件对象
     * @param fileType  文件类型（图片所属功能模块，作为图片保存子目录）
     * @return com.xydtech.common.core.domain.AjaxResult
     * @exception
     * @author JHON
     * @Date 2021/11/16 13:48
     **/
    @Log(title = "上传Cropper截图文件")
    @PostMapping("/common/uploadCropperImage")
    @ResponseBody
    public AjaxResult uploadCropperImage(@RequestParam("file") MultipartFile file, @RequestParam("fileType") String fileType) {
        try {
            if (!file.isEmpty()) {
                //当前机构号
                Long deptId = ShiroUtils.getSysUser().getDeptId();
                //根据当前机构查询法人机构
                SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(deptId);
                if (dept != null) {
                    deptId = dept.getDeptId();
                }
                //路径拼接法人机构号
                String filePath = XydtechBusiPlatConfig.getProfile() + "/" + deptId + fileType;
                String fileUrl = FileUploadUtils.upload(filePath, file, minioUpload);

                Map<String, Object> map = new HashMap<>();
                map.put("fileUrl", fileUrl);
                return AjaxResult.success(map);
            }
            return AjaxResult.error();
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
